#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <cstdio>
void ChildWrite(int wfd)
{
    char buffer[1024];
    char c = 0;
    int cnt = 0;
    while (true)
    {
        //snprintf(buffer, sizeof(buffer), "i am child say %d, cnt : %d", getpid(), cnt++);
        write(wfd, &c, 1);
        printf("%d\n",cnt++);
        //sleep(1);
    }
}
void FatherRead(int rfd)
{
    sleep(100);
    char buffer[1024];
    while (true)
    {
        int n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        break;
    }
}

int main()
{
    // 1.创建管道
    int fds[2];
    int n = pipe(fds);

    if (n < 0)
    {
        std::cout << "pipe error" << std::endl;
        return 1;
    }

    std::cout << "fds[0]: " << fds[0] << std::endl;
    std::cout << "fds[1]: " << fds[1] << std::endl;
    // 2.建立父子进程
    pid_t id = fork();
    if (id == 0)
    {
        // child
        close(fds[0]);
        ChildWrite(fds[1]);

        close(fds[1]);
        exit(0);
    }
    // 3.建立单向的信道 父进程读，子进程写
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);
    int status = 0;
    int ret = waitpid(id, &status, 0);
    if (ret > 0)
    {
        printf("status %d exit code %d,exit signal %d\n",status, (status >> 8) & 0xff, status & 0x7f);
        sleep(5);
    }

    return 0;
}
